package web;

import pojo.User;
import service.userService.userService;
import service.userServiceImpl.userServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;


@WebServlet("/registerServlet")
public class registerServlet extends HttpServlet {
    userService userservice=new userServiceImpl();
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username=req.getParameter("username");
        String password=req.getParameter("password");
        //创建用户对象并且进行封装
        User user=new User();
        user.setUsername(username);
        user.setPassword(password);
        HttpSession session=req.getSession();
        //获取用户输入的验证码
        String checkCode=req.getParameter("checkCodeText");
        //通过session获取生成的验证码数据
        String s=(String) session.getAttribute("s");
        //比较验证码
        if (!s.equalsIgnoreCase(checkCode)){
            String check_mistake="请把验证码看仔细";
            req.setAttribute("check_mistake",check_mistake);
            req.getRequestDispatcher("/register.jsp").forward(req,resp);
            return;
        }
        boolean b = userservice.selectByUsername(username);
        if (b){
            //存在该用户名
            String username_mis="该用户名已被占用，注册失败";
            req.setAttribute("reg_mistake",username_mis);
            req.getRequestDispatcher("/register.jsp").forward(req,resp);
        }else {
            userservice.add(user);
            String contextPath = req.getContextPath();
            resp.sendRedirect(contextPath+"/login.jsp");
        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req,resp);
    }
}
